package com.edg.service.impl;
import com.edg.service.UploadConService;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadConServiceImpl implements UploadConService {

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif","image/jpeg","image/jpg","image/bmp","image/png");

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadConServiceImpl.class);

    @Override
    public String uploadImage(MultipartFile file) {
        //校验文件类型
        String originaFilenmae = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTENT_TYPES.contains(contentType)){
            LOGGER.info("上传文件类型不合法: {}",originaFilenmae);
            return null;
        }
        //校验文件内容
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null){
                LOGGER.info("上传文件内容不合法: {}",originaFilenmae);
                return null;
            }
            //保存到服务器
            file.transferTo(new File("服务器路径" + originaFilenmae));
            //返回rul，进行回显
            return "服务器路径" + originaFilenmae;
        } catch (IOException e) {
            LOGGER.info("服务器内部错误" + originaFilenmae);
            e.printStackTrace();
        }
        return null;
    }
}
